<?php
// +----------------------------------------------------------------------
// | BIX [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016  All rights reserved.
// +----------------------------------------------------------------------
// | Author: @wangyejing
// +----------------------------------------------------------------------

namespace Home\Model;
use Think\Model;

/**
 * 购物车
 * @author wangyejing
 */

class CartModel extends Model
{
    /*s查询付款方式*/
    public function show()
    {
        $data = M('selectpay');
        $list = $data->select();
        return $list;
    }


    // 获取购物车信息
    public function goodsinfo(){

        $res             = I('post.');
        $session_info    = I('session.');

        //通过session获取userid
        $user_id         = $session_info['onethink_home']['user_id'];

        /*  获取user_id及goods_id和status */
        $data            = M('cart');
        $map['user_id']  = $user_id;
        $map['status']   = 0;  // 只查询状态为 1，为付款的商品
        $list            = $data->where($map)->select();

        foreach($list as $key => &$val){
            $val['goods_num'] += $val['num'];
            $val['sub_total'] += $val['num']*$val['price'];
            $val['cartid']     = $val['id'];
        }

        session('cart_info',$list);
        return $list;
    }


    //生成地址表
    public function addrinfo()
    {
        $session = I('session.');
        //大I方法
        $info = I('post.');
        if(!empty($info)){
            //切割城市省份
            $data['user_id'] = $session['onethink_home']['user_id'];
            $xx = explode("/",$info['area']);
            $data['province'] = $xx[0];
            $data['city'] = $xx[1];
            $data['country'] = $xx[2];
            $data['addr_detail']  = $info['street'];
            $data['phone']   = $info['phone'];
            $data['receiver'] = $info['name'];
            $data['postcode']= $info['postcode'];
            $data['status'] = 0;
            $res = M('user_addr');
            $info = $res->add($data);
             if($info){        // 如果主键是自动增长型 成功后返回值就是最新插入的值
                 $insertId = $info;
             }
            echo  $insertId;
        }else{
            echo false;
        }

    }


    /* 获取成功则返回地址信息,否则为空 */
    public function select_addr(){
        //通过session获得user_id
        $res = I('session.');

        $user_id =intval($res['onethink_home']['user_id']);

        //实例化地址表
        $data = M('user_addr');
        $map['user_id'] = array('eq',$user_id);
        $info = $data->where("user_id = $user_id")->order('status desc,addr_id desc')->limit(1)->select();
        return  $info;

    }


    /*  修改购物车表  */
    public function updatacart(){
        $info        = I('post.');
        $modi        = M('cart');
        $id          = $info['id']; // 购物车id
        $data['num'] = $info['num'];// 相应的更改数量
        $res         = $modi->where("id = $id")->save($data);
        return $res;
    }

    /*  删除购物车信息 */
    public function delcart(){
        $id             = I('post.id');
        $data['status'] = '-1';
        $res            = D('cart')->where("id = $id")->save($data);
        return $res;
    }

    /*  查询积分表  */
    public  function intergerinfo(){
        $res = I('session.');
        $id  = $res['onethink_home']['user_id'] + 0;
        $info = M('integralion');
        $list = $info->where("user_id = $id ")->getField('integral');

        return  $list;
    }

    //订单表与订单详情表生成
    public function addorder(){
        $idinfo  = I('post.');

        //取出积分数和付款方式id
        $jifen   = $idinfo['jifen'];
        $payid   = $idinfo['payment']['alipay_pay_bank'];

        //取出传参user_id/addr_id
        $user_id = $data['user_id'] = intval($idinfo['user_id']);
        $addr_id = $data['addr_id'] = intval($idinfo['addr_id']);

        //取出传参jifen/remark，积分
        $jifen             = $idinfo['jifen'];
        // 送货备注
        $data['remark']    = $idinfo['shipping'];

        //获取shop_time
        $data['shop_time'] = time();

        //实例化订单表和购物车表,订单详情表,地址表
        $orderinfo   = M('order');
        $modi        = M('cart');
        $orderdetail = M('order_detail');
        $addres      = M('user_addr');
        $payin       = M('selectpay');

        // 获取地址信息
        $addrinfo    = $addres->where("user_id={$user_id} and addr_id=$addr_id")->select();

        // print_r($addrinfo);exit;

        // 获取付款方式
        $payinfo     = $payin->where("id = $payid")->select();

        // 获取商品详情
        $cartinfo    = $modi->where("user_id = $user_id and  status = 0")->select();

        //遍历引用插入订单表
        $k = 0; //商品数量
        $t = 0; //商品总额

        // 准备一个空数组存放订单号，用于“立即支付”修改订单状态
        $order_num = [];
        foreach($cartinfo as $key =>&$val){

            $k += $val['num'];
            // 生成唯一订单号，沟通订单主从表的键
            $date = date('YmdHis',time()); // 当前时间戳的格式转换
            $res = $orderinfo->order('id desc')->limit(1)->getField('id');
            $maxnum = $res + 1; //订单表主键最大值加1
            $randnum = rand(0,9).rand(0,9).rand(0,9).rand(0,9); // 取四位随机数
            $orderid = "DD".$date.str_pad($maxnum,4,'0',STR_PAD_LEFT).$randnum; // 拼接成订单号

            // 包装订单号到$order_num
            $order_num[] = $orderid;

            //获得订单号
            $data['order_num'] = $orderid;
            $data['order_status'] = 0;
            $data['total']  = $val['price'] * $val['num'];

            $t += $data['total'];
            //事务开启
            D()->startTrans();

            //插入订单表
            $res1 = $orderinfo->add($data);

            //从订单表中获取其最大的id即当前的新加id
            $sql = "select max(id) as order_id from north_order";
            $info = [];
            $info = $orderinfo->query($sql);

            // 获取购物车内商品对应的尺码id、商品id和售出商品数量num
            $size = $val['size'];

            $details_id = D('details')->where("size like '{$size}'")->getField('details_id');

            //插入成功之后获购物车表的更多详情插入订单详情表
            $order_detail['goods_name'] = $val['goods_name'];
            $order_detail['price']      = $val['price'];
            $order_detail['good_num']   = $val['num'];
            $order_detail['goods_id']   = $val['goods_id'];
            $order_detail['details_id'] = $details_id;
            $order_detail['order_num']  = $orderid;
            //total
            $order_detail['total']      = $val['price'] * $val['num'];
            //user_id
            $order_detail['user_id']    = $idinfo['user_id'];
            //order_id
            $order_detail['order_id']   = $info[0]['order_id'];

            //插入订单详情表
            $res2 = $orderdetail->add($order_detail);

            /**
             * 修改库存和销量
             * @author Weiliqiang <[<email address>]>
             */

            $goods_id  = $val['goods_id'];

            // 此次售出商品数量
            $sale_num  = $val['num'];

            // 查询原有的库存和销量
            $old_info  = D('attr')->where("goods_id = $goods_id and details_id = $details_id")->Field('store,sale')->find();

            $old_store = $old_info['store'];
            $old_sale  = $old_info['sale'];

            $data['store'] = $old_store - $sale_num;
            $data['sale']  = $old_sale  + $sale_num;

            // 修改north_attr 的库存和销量数
            $res3 = D('attr')->where("goods_id = $goods_id and details_id = $details_id")->save($data);

            // 修改购物车north_cart的相应状态为1
            $info['status'] = 1;
            $res4 = D('cart')->where("goods_id = $goods_id and user_id = $user_id")->save($info);

            //事务回滚
            if($res1 && $res2 && $res3 && $res4){
                D()->commit();
            }else{
                D()->rollback();
            }
        }

        //返回购物车信息,地址表信息,备注信息,user_id
        return ['cartinfo'=>$cartinfo,'addrinfo'=>$addrinfo,'remark'=>$data['remark'],'userid'=>$user_id,'jifen'=>$jifen,'payinfo'=>$payinfo,'k'=>$k,'t'=>$t,'order_num'=>$order_num];
    }


    //付款成功修改订单状态
    public function modifyorder($pay_order_num=array())
    {
        // 根据session获取用户id
        $uid = session()['user_id'];

        // 循环修改订单号状态
        $data['order_status'] = '2';
        foreach($pay_order_num as $v){
            $res = D('order')->where("user_id=$uid and order_num='{$v}' and order_status=0")->save($data);
        }

        // 修改订单状态后，将session中的order_num 清空
        session('order_num',null);
    }

    public function modifyinteger()
    {
        $userid = I('post.');

        $sole   = intval($userid['sole']);
        $inter  = M("integralion"); // 实例化integralion对象

        //条件,获得积分和id
        $ji     = intval($userid['jifen']);
        $uid    = session()['user_id'];

        //查询积分表
        $sql    = "select integral from north_integralion where user_id=$uid order by id desc limit 1";
        $res    = $inter->query($sql);

        //查询原来的积分
        $res    = $res[0]['integral'];
        $res    = intval($res);
        $data['user_id']      = intval($userid['userid']);
        if($ji !== 0){
            $data['type']     = '使用';
            //新积分数=原本积分-使用积分
            $data['integral'] = $res - $ji;
            $data['payfor']   = "-$ji";
            $data['ctime']    = time();
            $data['status']   = 0;
            $inter->add($data);// 根据条件更新记录
        }
        $ji    = ceil($sole/100);
        $data['type'] = "消费";
        $data['integral'] = $res + $ji;
        $data['payfor']  = "+$ji";
        $data['ctime']  = time();
        $data['status'] = 0;
        $inter->add($data);
        return  ['sole'=>$sole];
    }
}
